<template>
  <ContentWrap>
    <!--    顶部查询项-->
    <el-form :model="form" inline>
      <el-form-item :label="t('orderPayment.transactionTicketNumber')">
        <el-input
          v-model="form.voucher_code"
          clearable
          :placeholder="t('orderPayment.transactionTicketNumber')"
          style="width: 250px"
        />
      </el-form-item>
      <el-form-item :label="t('orderPayment.theTypeOfOrder')">
        <el-select
          v-model="form.order_type"
          :placeholder="t('orderPayment.theTypeOfOrder')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in orderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderPayment.paymentType')">
        <el-select
          v-model="form.pay_type"
          :placeholder="t('orderPayment.paymentType')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in payTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderPayment.paymentStatus')">
        <el-select
          v-model="form.pay_status"
          :placeholder="t('orderPayment.paymentStatus')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('common.creator')">
        <el-select
          v-model="form.creator"
          :placeholder="t('common.creator')"
          :clearable="true"
          style="width: 250px"
        >
          <el-option
            v-for="item in creatorList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="t('orderPayment.paymentTime')">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          range-separator="-"
          :start-placeholder="t('common.startTimeText')"
          :end-placeholder="t('common.endTimeText')"
          @change="changeTime"
          :editable="false"
          unlink-panels
          clearable
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="initialize">{{
          t('common.search')
        }}</el-button>
        <el-button icon="Refresh" @click="reset">{{ t('common.reset') }}</el-button>
      </el-form-item>
    </el-form>

    <div class="flex flex-items-center my-5">
      <el-button type="primary" v-hasPermi="['PaymentExport']" @click="handleExport">
        {{ t('action.exportFile') }}
      </el-button>
    </div>
    <!-- 表格主体 -->
    <Table
      showAction
      :data="dataList"
      :columns="tableColumns"
      highlight-current-row
      stripe
      border
      :loading="tableLoading"
      align="center"
      header-align="center"
      row-key="id"
    />
    <!--    分页-->
    <Pagination
      :total="paginationTotal"
      v-model:page="form.pageIndex"
      v-model:limit="form.pageSize"
      @pagination="initialize"
    />
    <!--      支付信息审核弹框-->
    <DialogAudit ref="DialogAuditRef" @refresh="initialize" />
  </ContentWrap>
</template>

<script setup lang="ts">
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination/index.vue'
import DialogAudit from '@/components/OrderPayment/DialogAudit/index.vue'
import { ContentWrap } from '@/components/ContentWrap'
import { useEnumeratePicker } from '@/utils'
import { getPayEnumApi, getListApi, exportDataApi } from '@/api/order/pay'
import { usePermissionStoreWithOut } from '@/store/modules/permission'
import { getSelectListApi as getOperatorSelectListApi } from '@/api/operator'
import { Table } from '@/components/Table'
// @ts-ignore
import { useOrderPaymentTableColumns } from './components/hooks/useTableColumns'
import { ElMessage } from 'element-plus'
const permissionStore = usePermissionStoreWithOut()

const { t } = useI18n()
const { push } = useRouter()

const tableLoading = ref<boolean>(false)
const dataList = ref<any[]>([])
const paginationTotal = ref<number>(0)
const DialogAuditRef = ref<InstanceType<typeof DialogAudit>>()

const form = ref<Record<string, any>>({
  voucher_code: '',
  order_type: '',
  pay_type: '',
  pay_status: '',
  date: [],
  start_time: '',
  end_time: '',
  creator: '',
  pageIndex: 1,
  pageSize: 20
})

const orderStatusList = ref<Array<Record<string, any>>>([])
const orderTypeList = ref<Array<Record<string, any>>>([])
const paymentMethodList = ref<Array<Record<string, any>>>([])
const statusList = ref<Array<Record<string, any>>>([])
const payTypeList = ref<Array<Record<string, any>>>([])
const currencyList = ref<Array<Record<string, any>>>([])
const transferTypeList = ref<Array<Record<string, any>>>([])
const creatorList = ref<Array<Record<string, any>>>([])

//格式化时间
const changeTime = (e: Date[]) => {
  if (e && e.length > 0) {
    form.value.start_time = dayjs(e[0]).format('YYYY-MM-DD 00:00:00')
    form.value.end_time = dayjs(e[1]).format('YYYY-MM-DD 23:59:59')
  } else {
    form.value.start_time = null
    form.value.end_time = null
  }
}

//打开支付信息审核弹框
const handleAudit = (row: Record<string, any>) => {
  nextTick(() => {
    DialogAuditRef.value!.dialogVisible = true
    DialogAuditRef.value?.getBackShow(row)
  })
}

//点击跳转
const handleJump = (type: string, row?: Record<string, any>) => {
  push({
    path: `/order/orderPayment/${type}`,
    query: { data: encodeURIComponent(JSON.stringify(row)) }
  })
}
const handleLink = (type: string, row: any) => {
  let path = ''
  if (type === 'detail') {
    path =
      row?.order_type === 'order'
        ? '/order/order-management/detail'
        : '/order/wholesal-order-management/detail'
    push({
      path: path,
      query: { id: row?.order_id }
    })
  } else if (type === 'customer') {
    push({
      path: `/customer/customerList/detail`,
      query: { id: row?.user_id }
    })
  }
}

//获取枚举
const getDropDownBoxInfo = async () => {
  const resp = await getPayEnumApi({ field: 'all' })
  orderTypeList.value = resp.data.order_type
  statusList.value = resp.data.status
  paymentMethodList.value = resp.data.payment_method
  currencyList.value = resp.data.currency
  orderStatusList.value = resp.data.order_status
  payTypeList.value = resp.data.pay_type
  transferTypeList.value = resp.data.transfer_type

  const signatoryResp = await getOperatorSelectListApi({})
  creatorList.value = signatoryResp.data.list
}

//初始化请求
const initialize = async () => {
  tableLoading.value = true
  const params = JSON.parse(JSON.stringify(form.value))
  delete params.date
  const resp = await getListApi(params)
  dataList.value = resp.data.list
  paginationTotal.value = resp.data.total
  tableLoading.value = false
}

//重置查询项
const reset = () => {
  form.value = {
    voucher_code: '',
    order_type: '',
    pay_type: '',
    pay_status: '',
    date: [],
    start_time: '',
    end_time: '',
    creator: '',
    pageIndex: 1,
    pageSize: 20
  }
  paginationTotal.value = 0
  initialize()
}

//导出数据
const handleExport = async () => {
  try {
    const params = JSON.parse(JSON.stringify(form.value))
    delete params.date
    delete params.pageIndex
    delete params.pageSize

    const filename = `Payment_${dayjs().format('YYYY-MM-DD_HH-mm-ss')}.xlsx`

    await exportDataApi(params, filename)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}
const reviewPermission = ref(false)
onMounted(() => {
  reviewPermission.value = false
  console.log('permissionStore1111', permissionStore.$state.addRouters)
  permissionStore.$state.addRouters.forEach((route) => {
    if (route.name === 'Order') {
      route.children?.forEach((child) => {
        if (child.name === 'OrderPayment') {
          child.children?.forEach((child2) => {
            if (child2.name === 'OrderPaymentReview') {
              reviewPermission.value = true
            }
          })
        }
      })
    }
  })
  console.log('reviewPermission', reviewPermission.value)
  getDropDownBoxInfo()
  initialize()
})

const tableColumns = useOrderPaymentTableColumns(
  handleLink,
  handleAudit,
  useEnumeratePicker,
  paymentMethodList,
  orderStatusList,
  statusList,
  orderTypeList,
  payTypeList,
  currencyList,
  transferTypeList,
  creatorList,
  dataList,
  reviewPermission
)
</script>

<style lang="less" scoped></style>
